package com.easyWeb.interceptor;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.function.Predicate;

@Slf4j
@Data
public class JwtInterceptor implements HandlerInterceptor {

    private String jwtName;
    private Predicate<String> jwtValid;
    private String token;

    public JwtInterceptor(String jwtName, Predicate<String> jwtValid ) {
        this.jwtName = jwtName;
        this.jwtValid=jwtValid;
    }

    /**
     * Jwt拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("JwtInterceptor（Jwt拦截器开始运行）开始运行");
        if(!(handler instanceof HandlerMethod)){
            log.info("JwtInterceptor: 当前拦截并非方法，放行");
            return true;
        }
        log.info("正在从 header 获取令牌");
        token = request.getHeader(jwtName);
        if (token==null){
            log.info("令牌为空");
            return false;
        }
        try{
            log.info("正在校验令牌:{}", token);
            if (!jwtValid.test(token)){
                log.info("令牌校验失败");
                return false;
            }
            log.info("令牌校验成功");
            return true;

        }catch (Exception e){
            log.error("令牌校验出错");
            response.setStatus(401);
            return false;
        }
    }

}
